package com.wind.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 阿里云短信服务
 */
@Component
public class SMS {

    private static String active;

    private static String sms;

    private static String accessKeyId;

    private static String secret;


    @Value("${spring.profiles.active}")
    public void setActive(String active) {
        active = active;
    }


    @Value("${platform.sms}")
    public void setSms(String sms) {
        sms = sms;
    }

    public static String getSms() {
        return sms;
    }

    
    @Value("${platform.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        accessKeyId = accessKeyId;
    }


    @Value("${platform.secret}")
    public void setSecret(String secret) {
        secret = secret;
    }


    /**
     * 发送手机短信
     * @param phone        手机号码
     * @param templateCode 短信模板编码(0:登录验证码短信, 1:账户冻结通知短信, 2:活动提醒短信)
     * @return Boolean false: 失败, true:成功
     * @author JasonTsangLai
     * @date 2019-05-08
     */
    public static Boolean send(String phone, Integer templateCode, HttpServletRequest request) {
        // 正式环境才发送
        Boolean bool = false;
        Map<String, Object> map = SMSUtil.SendSms(phone);
        System.out.println(map.toString());
        if("200".equals(map.get("code").toString())){
            bool=true;
        }else {
            bool=false;
        }

        return bool;
    }


    // 日志
    private static void getJSON(String phone, Integer code, Long time, String message) {
        JSONObject json = new JSONObject();
        json.put("phone", phone);
        json.put("code", code);
        json.put("time", time + "秒");
        json.put("message", message);
        System.out.println("手机短信缓存成功 => " + json.toString());
    }


    /**
     * 获取手机短信登录验证码
     * @param phone    手机号码
     * @return Integer 登录验证码
     * @author JasonTsangLai
     * @date 2019-05-08
     */
    public static String get(String phone) {
        Object coding = RedisUtil.get(KeyPrefixConst.key_sms+phone);
        String code = null == coding ? null : coding.toString();
        String failure = phone + "的短信登录验证码已失效";
        String success = phone + " 的短信登录验证码为 => " + code;
        System.out.println(null == code ? failure : success);
        return code;
    }

}
